package cn.hairui.fastms.core.controller;


import cn.hairui.fastms.base.cache.CacheManage;
import cn.hairui.fastms.base.config.WebLogInfo;
import cn.hairui.fastms.constant.ConfigConstant;
import cn.hairui.fastms.constant.GlobalConstant;
import cn.hairui.fastms.core.bean.SUser;
import cn.hairui.fastms.core.bean.SUserTheme;
import cn.hairui.fastms.core.service.SUserThemeService;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户主题配置 前端控制器
 * </p>
 *
 * @author lihairui
 * @since 2020-12-31
 */
@Controller
@RequestMapping("/sUserTheme")
public class SUserThemeController {
    @Autowired
    private SUserThemeService sUserThemeService;


    @WebLogInfo(description = "获取用户主题样式")
    @RequestMapping(value = "/theme")
    @ResponseBody
    @Transactional
    public String theme(HttpServletRequest request) {
        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        Map themeMap = new HashMap<>();
        if (sUser == null) {
            themeMap.put("theme", CacheManage.configMap.get(ConfigConstant.CFG_SYSTEM_DEFAULT_THEME));
        } else {
            //获取用户配置主题
            String userAccount = sUser.getUserAccount();
            SUserTheme sUserTheme = sUserThemeService.getById(userAccount);
            themeMap.put("theme", sUserTheme == null ? CacheManage.configMap.get(ConfigConstant.CFG_SYSTEM_DEFAULT_THEME) : sUserTheme.getThemeId());
        }
        return JSONObject.toJSONString(themeMap);
    }

    @WebLogInfo(description = "保存用户主题样式")
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional
    public String save(HttpServletRequest request, String themeName) {
        SUser sUser = (SUser) request.getSession().getAttribute(GlobalConstant.GLOBAL_SESSION_NAME);
        if (sUser != null && themeName != null && !"".equals(themeName)) {
            SUserTheme sUserTheme = new SUserTheme();
            sUserTheme.setUserAccount(sUser.getUserAccount());
            sUserTheme.setThemeId(themeName);
            sUserThemeService.saveOrUpdate(sUserTheme);
            return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0000).toJSONString();
        } else {
            return CacheManage.msgMap.get(GlobalConstant.MSG_CDE_S0001).toJSONString();
        }
    }
}

